package kk.servlet;

import com.google.gson.Gson;
import kk.domain.User;
import kk.service.UserService;
import kk.service.impl.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService userService=new UserServiceImpl();
        User loginUser = userService.login(user);
        if (loginUser==null){
            //登录失败,将信息存到request域中，并跳转到login.jsp
            request.setAttribute("msg","用户名或密码错误");
            request.setAttribute("username",user.getUsername());
            request.setAttribute("password",user.getPassword());
            request.getRequestDispatcher("/pages/user/login.jsp").forward(request,response);
        }else {
            //登录成功
            //将用户信息存到session
            request.getSession().setAttribute("user",user);
            request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request,response);
        }
    }

    protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        //从session中获取验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //从session中删除验证码
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //获取前台输入的用户信息
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //获取客户端输入的验证码
        String code = request.getParameter("code");
        if (code!=null && token.equalsIgnoreCase(code)){
            //验证码相同，开始注册
            UserService userService=new UserServiceImpl();
            boolean registOk = userService.regist(user);
            if (registOk){
                //注册成功
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            }else {
                //注册失败,保存信息，跳转到regist.jsp
                request.setAttribute("msg","用户名已存在");
                request.setAttribute("username",user.getUsername());
                request.setAttribute("email",user.getEmail());
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }
        }else {
            request.setAttribute("msg","验证码输入错误");
            request.setAttribute("username",user.getUsername());
            request.setAttribute("email",user.getEmail());
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }

    /**
     * 注销用户
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().removeAttribute("user");
        response.sendRedirect(request.getContextPath());
    }

    /**
     * ajax验证用户名是否可用
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        UserService userService=new UserServiceImpl();
        boolean flag = userService.exitUsername(username);
        Map<String,Object> map=new HashMap();
        map.put("exitUsername",flag);
        Gson gson=new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);

    }


}
